﻿namespace Pyramid.Hardware.Gates
{
	using System.Linq;

	/// <summary>
	/// Implements line precedence - if A =/= Unknown, then output A; else
	/// output B. That is to say, the value of A (if known) takes precedence
	/// over the value of B.
	/// </summary>
	/// <remarks>
	/// Internally, this is implemented as a line multiplexer - input A is used
	/// as the selector line, the True input and the False input; input B is
	/// used as the Unknown input. Thus, if input A is True or False, it will
	/// be selected as the output, otherwise input B will be selected.
	/// </remarks>
	public class PrecedenceGate
		: Gate
	{
		/// <summary>
		/// Initializes an instance of the PrecedenceGate class.
		/// </summary>
		/// <param name="inputLineA"></param>
		/// <param name="inputLineB"></param>
		public PrecedenceGate(ILine inputLineA, ILine inputLineB)
		{
			// Refactoring this out by explicitly creating the gates would
			// optimise this slightly, but it shouldn't be a performance issue
			// in the immediate future.
			var lineSelector = new BusMultiplexer(inputLineA,
												inputLineA, inputLineB, inputLineA);

			this.WrapOutputLine(lineSelector.OutputBus.First());
		}
	}
}
